import { inject, reactive } from "vue";

export function createStore(options) {
  return new Store(options);
}

export const storeKey = "store";

export class Store {
  constructor(options = {}) {
    this.options = options;

    this._state = reactive({
      data: this.options.state(),
    });
  }

  install(app, injectKey) {
    // 定义 provide
    app.provide(injectKey || storeKey, this);
  }

  // 调用 mutations 中的方法
  commit(_type, _params) {
    const { mutations } = this.options;
    const fn = mutations[_type];
    if (fn) {
      fn(this.state, _params);
    }
  }

  get state() {
    return this._state.data;
  }
}

export function useStroe(key = null) {
  return inject(key !== null ? key : storeKey);
}
